<?php
/**
 * Created by PhpStorm.
 * User: lcz
 * Date: 2018/1/26
 * Time: 11:38
 * //电话控制器
 */
namespace fast;

class Flow
{

    //对接卡池
    protected static $iotUrl = '';
    protected static $iotUser = '';
    protected static $iotKey = '';
    protected static $delimiter = '&';

    protected static $devUser = '';
    protected static $devKey = '';

    //对接运营商
    protected static $devUserPwd = '';
    protected static $devUrl = '';

    public static $devFlag = 0;//是否对接卡池
    public static $devLogin = '';

    public static function init(array $config)
    {
        /**
         * 初始化物联卡配置
         */
        self::$iotUrl = isset($config['pool_url']) ? $config['pool_url'] :'' ;//AppConfig::search(['merid'=>$merid,'key'=>'iotUrl'],['field'=>'value']);
        self::$iotUser = isset($config['card_user']) ? $config['card_user'] :'' ;//AppConfig::search(['merid'=>$merid,'key'=>'iotUser'],['field'=>'value']);
        self::$iotKey = isset($config['card_key']) ? $config['card_key'] :'' ;//AppConfig::search(['merid'=>$merid,'key'=>'iotKey'],['field'=>'value']);
        self::$devUser = isset($config['dev_user']) ? $config['dev_user'] :'' ;
        self::$devKey = isset($config['dev_key']) ? $config['dev_key'] :'' ;
        self::$devFlag = isset($config['mode']) ? $config['mode'] :'' ;
        self::$devLogin = isset($config['ejion_login']) ? $config['ejion_login'] :'' ;
        self::$devUserPwd = isset($config['ejion_user']) && isset($config['ejion_pwd']) ? $config['ejion_user'].':'.md5($config['ejion_pwd']) :'' ;
        self::$devUrl = isset($config['ejoin_url']) ? $config['ejoin_url'] :'' ;//AppConfig::search(['merid'=>$merid,'key'=>'devUrl'],['field'=>'value']);


    }

    /**
     * 获取sign
     * @param $params
     * @param string $func
     * @param string $delimiter
     * @param string $mode
     * @param string $salt
     * @return string
     */
    public static function getSign($params,$mode='normal',$salt='',$delimiter='',$func='MD5'){
        $ret = '';
        if($mode=='normal')
        {
            $ret = $func(implode($delimiter,$params));
        }
        else if($mode=='salt_sort')
        {
            ksort($params);
            $ar_tmp = [];
            foreach ($params as  $k=>$v)
            {
                $ar_tmp[] = "{$k}={$v}";
            }
            $ret = $func(implode($delimiter,$ar_tmp).$delimiter.$salt);
        }
        else if($mode=='key_salt')
        {
            $params['key']=$salt;
            $ar_tmp = [];
            foreach ($params as  $k=>$v)
            {
                $ar_tmp[] = "{$k}={$v}";
            }
            $ret = $func(implode($delimiter,$ar_tmp));
        }
        else if($mode=='key_salt_sort')
        {
            ksort($params);
            $params['key']=$salt;
            $ar_tmp = [];
            foreach ($params as  $k=>$v)
            {
                $ar_tmp[] = "{$k}={$v}";
            }
            $str = implode($delimiter,$ar_tmp);
            self::logWrite($str);
            $ret = $func($str);
        }
        return $ret;
    }

    public static function staticCurlRequest($url, $postdata = [],$timeOut=300) {
        $ch = curl_init ();
        curl_setopt($ch, CURLOPT_URL,    $url);
        curl_setopt($ch, CURLOPT_HEADER,    0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,    1);
        curl_setopt($ch, CURLOPT_TIMEOUT,    $timeOut);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,    false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,    false);
        if (isset($postdata ['user_pwd'])) {
            curl_setopt($ch, CURLOPT_USERPWD,    $postdata['user_pwd']);
            curl_setopt($ch, CURLOPT_HTTPAUTH,    CURLAUTH_BASIC);
            unset ( $postdata ['user_pwd'] );
        }
        if(isset($postdata ['action']))
        {
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST,    $postdata['action']);
            unset ( $postdata ['action'] );
        }
        if ($postdata) {
            curl_setopt($ch, CURLOPT_POST,    1);
            curl_setopt($ch, CURLOPT_POSTFIELDS,    $postdata);
        };
        $response = curl_exec ( $ch );
        $msg = '';
        if($response === false){
            $msg = 'Curl error: ' . curl_error($ch);
        }
        curl_close ( $ch );
        if($msg)
        {
            $data = ['code'=>-12,'msg'=>$msg];
            $response = json_encode($data);
        }
        return $response;
    }
    public static function logWrite($msg,$dir='')
    {
        if(!$dir)
        {
            $request = \think\Request::instance();
            $dir = RUNTIME_PATH.$request->module().DS.$request->controller().DS.$request->action().DS;

        }
        \think\Log::init(['path'=>$dir]);
        \think\Log::write($msg);
        \think\Log::init(['path'=>LOG_PATH]);
    }
    /**
     * 执行查询（对接卡池）
     * @param string $path
     * @param array $params
     * @return mixed
     */
    public static function query($path,$params=[])
    {
        $params['u'] = self::$iotUser;
        $params['s'] = isset($params['s'])? $params['s'] : self::getSign($params,'key_salt_sort',self::$iotKey,self::$delimiter);
        $url = self::$iotUrl.$path.'?'.http_build_query($params);
        $res = self::staticCurlRequest($url);
        self::logWrite($url.'------'.$res);
        return json_decode($res,true);
    }



    /**
     * 执行查询（对接卡池）
     * @param string $path
     * @param array $params
     * @return mixed
     */
    public static function queryDev($path,$params=[])
    {
        $params['u'] = self::$devUser;
        $params['s'] = isset($params['s'])? $params['s'] : self::getSign($params,'key_salt_sort',self::$devKey,self::$delimiter);
        $url = self::$iotUrl.$path.'?'.http_build_query($params);
        $res = self::staticCurlRequest($url);
        self::logWrite($url.'------'.$res);
        return json_decode($res,true);
    }

    /**CARD API START================================================================================================**/
    /**
     * 查询卡状态
     * @param string $iccid
     * @param string $isp
     * @param string $flag
     * @return mixed
     */
    public static function setCardStatus($iccid,$isp='telecom',$flag='19')
    {
        return self::query('/disabledNumber',['ic'=>$iccid,'is'=>$isp,'t'=>$flag]);
    }

    /**
     * 卡报备
     * @param string $iccid
     * @param string $isp
     * @return mixed
     */
    public static function onRecord($iccid,$isp='telecom')
    {
        return self::query('/onRecord',['ic'=>$iccid,'is'=>$isp]);
    }

    /**
     * 查询卡状态
     * @param string $iccid
     * @param string $isp
     * @return mixed
     */
    public static function getCardStatus($iccid,$isp='telecom')
    {
        return self::query('/queryCardStatus',['ic'=>$iccid,'is'=>$isp]);
    }

    /**
     * 查询有效期
     * @param string $iccid
     * @param string $isp
     * @return mixed
     */
    public static function getCardValid($iccid,$isp='telecom')
    {
        return self::query('/queryValidDate',['ic'=>$iccid,'is'=>$isp]);
    }

    /**
     * 查询套餐
     * @param string $iccid
     * @param string $isp
     * @return mixed
     */
    public static function getCardPkg($iccid,$isp='telecom')
    {
        return self::query('/queryPakage',['ic'=>$iccid,'is'=>$isp]);
    }

    /**
     * 续费或者预充
     * @param string $iccid
     * @param string $goods_id
     * @param string $isp
     * @param string $serial_no
     * @param string $order_id
     * @return mixed
     */
    public static function orderFixed($iccid,$goods_id='',$isp='telecom',$serial_no='',$order_id='')
    {
        return self::query('/orderFixed',['ic'=>$iccid,'is'=>$isp,'serial_no'=>$serial_no,'g'=>$goods_id,'orderno'=>$order_id]);
    }

    /**
     * 充值叠加包
     * @param string $iccid
     * @param string $goods_id
     * @param string $isp
     * @param string $serial_no
     * @param string $order_id
     * @return mixed
     */
    public static function orderFlow($iccid,$goods_id,$isp='telecom',$serial_no='',$order_id='')
    {
        return self::query('/orderFlow',['ic'=>$iccid,'is'=>$isp,'serial_no'=>$serial_no,'g'=>$goods_id,'orderno'=>$order_id]);
    }

    /**
     * 获取卡批次
     * @return mixed
     */
    public static function pullTaskList()
    {
        return self::query('/pullTaskIds');
    }

    /**
     * 按照批次拉取卡
     * @param string $taskid
     * @return mixed
     */
    public static function pullCards($taskid)
    {
        return self::query('/pullTaskIds',['taskid'=>$taskid]);
    }

    /**CARD API END==================================================================================================**/

    /**DEVICE API START==============================================================================================**/
        /**对接运营商 START-------------------------------------------------------------------------------------------**/
        protected static $enumMap = array(
            'APP_130021_USER_NOT_FOUND'=>'用户未找到',
            'APP_130051_DEVICE_NOT_FOUND'=>'设备未找到',
            'APP_130056_DEVICE_EXIST'=>'设备已存在',
            'APP_130070_DEVICE_GROUP_NOT_FOUND'=>'设备组未找到',
            'APP_130071_DEVICE_GROUP_EXIST'=>'设备组已存在',
            'APP_130076_AREA_NOT_FOUND'=>'地区未找到',
            'APP_130080_SUITE_NOT_FOUND'=>'套餐未找到',
            'APP_130082_SUITE_NOT_BELONG_DEV'=>'套餐和设备不匹配',
            'APP_130090_DEVICE_GROUP_UNAUTHORIZED_OPERATION'=>'设备组不属于操作者',
            'APP_130090_SUITE_UNAUTHORIZED_OPERATION'=>'套餐不属于操作者',
            'APP_130090_DEVICE_UNAUTHORIZED_OPERATION'=>'设备不属于操作者',
            'APP_400_BAD_REQUEST'=>'请求有误，服务端没有进行相应操作。',
            'APP_406_NOT_ACCEPTABLE'=>'请求的格式不可得。',
            'APP_408_REQUEST_TIMEOUT'=>'请求超时。',
            'APP_500_SERVER_ERROR'=>'运营商服务器内部错误。',
        );
        /**
         * 发送请求
         * @param string $path
         * @param string $action
         * @param array $postdata
         * @return mixed
         */
        public static function sendRequest($path,$action='GET',$postdata=array())
        {

            $url = self::$devUrl.$path;
            if($postdata)
            {
                $url .= "?".http_build_query($postdata);
            }
            $ret = self::staticCurlRequest($url,['user_pwd'=>self::$devUserPwd,'action'=>$action]);
            $arr = json_decode($ret,true);
            if(!isset($arr['code']) || !count($arr))
            {
                $arr['code']=-12;
                $arr['msg']='Request：'.$url.'====》'.$ret;
            }
            else
            {
                if($arr['code']!=0)
                {
                    $arr['msg']=self::$enumMap[$arr['reason']];
                }
            }
            if($arr['code']!=0)
            {
                self::logWrite($url.'------'.$arr['msg']);
            }
            return $arr;
        }

        /**
         * 设备接口
         * @param string $devid
         * @param string $action
         * @param array $postData
         * @return mixed
         */

        public static function DeviceOpt($devid,$action='GET',$postData=array())//设备查询
        {
            if($action=='GET')
            {
                $postData = array("devid"=>$devid);
            }
            return self::sendRequest('/apiv2/wifidevice',$action,$postData);
        }

        /**
         * 套餐接口
         * @param $devid
         * @param string $action
         * @param array $postData 增加套餐['devid'=>$vid, 'areaid'=> 'u.as.cn', 'remain'=> $pkg*1000, 'effectDate'=> str(util.do_date()), 'invalidDate'=> date("Y-m-d H:i:s"),'limitValue'=> 0, 'rateLimit': 0, 'idxExtPkgId': $goods_id, 'pkgPrice': $price*1000, 'suiteState': 2, 'suiteExpire':$month*365*24/12, 'orderPkgType': 'T', 'idxOrderID': substr(date("Y"),2).date("mdHis").mt_rand(100,999).$vid.mt_rand(1000,9999)]
         * @return mixed
         */
        public static function DevicePkgOpt($devid,$action='GET',$postData=array())//设备套餐查询
        {
            if($action=='GET')
            {
                $postData = array("devid"=>$devid);
            }
            return self::sendRequest('/apiv2/devicepkg',$action,$postData);
        }

        /**对接运营商 END---------------------------------------------------------------------------------------------**/

        /**对接卡池 START---------------------------------------------------------------------------------------------**/
        /**
         * 设备报备
         * @param string $devid
         * @return mixed
         */
        public static function onDevRecord($devid)
        {
            return self::queryDev("/onDevRecord",['devid'=>$devid]);
        }
        /**
         * 充值叠加包
         * @param string $devid
         * @param string $goods_id
         * @param string $serial_no
         * @param string $order_id
         * @return mixed
         */
        public static function orderDevFlow($devid,$goods_id,$serial_no='',$order_id='')
        {
            return self::queryDev('/orderDevFlow',['devid'=>$devid,'serial_no'=>$serial_no,'g'=>$goods_id,'orderno'=>$order_id]);
        }
        /**
         * 设备信息
         * @param string $devid
         * @return mixed
         */
        public static function queryDevInfo($devid)
        {
            return self::queryDev("/queryDevInfo",['devid'=>$devid]);
        }

        /**
         * 设置设备状态
         * @param string $devid
         * @param string $flag
         * @return mixed
         */
        public static function setDevStatus($devid,$flag='19')
        {
            return self::queryDev("/setDevStatus",['devid'=>$devid,'t'=>$flag]);
        }
        /**对接卡池 END-----------------------------------------------------------------------------------------------**/
    /**DEVICE API END================================================================================================**/


    /**
     * 双卡设备关联接口
     * @param $imei
     * @param string $phone
     * @param bool $isBind
     * @return array
     */
//    protected static $MIFI_API = 'http://wifi.075511185.com/api/h5/';
    protected static $MIFI_API = 'http://wifi.168call.cn/api/h5/';
    public static function devOperate($api,$imei, $phone='', $isBind=false)
    {
        $data = ['imei'=>$imei, 'ts'=>time()];
        if(!$imei)
        {
            return ['code'=>400,'msg'=>'设备号不能为空'];
        }
        if($isBind)
        {
            if(!$phone)
            {
                return ['code'=>400,'msg'=>'手机号不能为空'];
            }
            $data['phone'] = $phone;

        }
        $options = [CURLOPT_FOLLOWLOCATION=>0];
        $apiUrl = self::$MIFI_API.$api;
        $params = '?params='.base64_encode(json_encode($data));
        $ret = Http::get(self::$MIFI_API.'sign'.$params,[],$options);
        if(!$ret)
        {
            return ['code'=>400,'msg'=>'签名失败'];
        }
        $signArr = \GuzzleHttp\json_decode($ret,true);
        $data['sign'] = $signArr['data']['sign'];
        $res = Http::post($apiUrl,$data,$options);
        if(!$res)
        {
            return ['code'=>400,'msg'=>'操作失败'];
        }
        return \GuzzleHttp\json_decode($res,true);
    }
}